""" player - Player class """

import logging

class Player(object):
    """
    Represents an active player in the current game.
    """

    rank = None
    boss = None
    boats = None
    money = 0
    reputation = 0
    game = None
    world = None

    log = logging.getLogger('engine.player')

    def __init__(self, game, world):
        self.game = game
        self.world = world
        self.boats = []
        self.boatsThisTurn = []

    def move(self):
        """
        Execute the boat movement plotted.
        """
        for boat in self.boats:
            boat.move()

    def animMove(self, percentInc=15.0):
        gens = [(ship, ship.animate()) for ship in self.boats]
        while len(gens):
            ship, iter = gens.pop(0)
            try:
                newPos = iter.next()
            except StopIteration:
                pass
            else:
                yield ship, newPos
                gens.append((ship, iter))
            
    def crewActions(self):
        """
        Make each pirate perform his assigned duty.
        """
        for boat in self.boats:
            boat.crewActions()

    def startTurn(self):
        """
        Get ready for a new turn.
        """
        #TODO: Launch this in a seperate thread, set an event before return.
        self.log.debug('Starting a turn.')
        self.boatsThisTurn = []
        for boat in self.boats:
            boat.startTurn()
        if not len(self.boatsThisTurn):
            self.finishTurn()

    def onBoatStarted(self, ship):
        """
        Keep track of started boats for this turn.
        """
        assert ship not in self.boatsThisTurn
        self.boatsThisTurn.append(ship)

    def onBoatRestarted(self, ship):
        """
        Keep track of started boats for this turn.
        """
        assert ship not in self.boatsThisTurn
        self.boatsThisTurn.append(ship)


    def onBoatFinished(self, ship):
        """
        Keep track of finished boats for this turn.
        """
        assert ship in self.boatsThisTurn
        self.boatsThisTurn.remove(ship)
        if len(self.boatsThisTurn) == 0:
            self.finishTurn()

    def finishTurn(self):
        """
        Complete a turn.
        """
        self.game.onPlayerFinished(self)

